<template>
  <div class="app-container">
    <el-form :inline="true" :model="checkoutData" class="demo-form-inline">
      <el-form-item label="商品名称">
        <el-input v-model="checkoutData.name" placeholder="商品名称"></el-input>
      </el-form-item>
      <el-form-item label="商品类别">
        <el-cascader :options="orderList" :props="{value:'id',label:'name'}" v-model="checkoutData.categoryId" @change="goodClassChange"></el-cascader>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="check">查询</el-button>
      </el-form-item>
      <el-button icon="el-icon-refresh" @click="handleReset">
        重置
      </el-button>
    </el-form>
    <el-button type="primary" @click="handleAdd">
      新增
    </el-button>
    <el-button type="primary" @click="openJoinPage">
      加入公司商品库
    </el-button>
    <el-button type="primary" @click="confirmDele">
      删除商品
    </el-button>

    <el-table :data="dataList" @selection-change="handleSelectionChange" style="width: 100%;margin-top:30px;" border>
      <el-table-column
        type="selection">
      </el-table-column>
      <el-table-column align="center" label="商品名称" width="220">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="商品条码" width="220">
        <template slot-scope="scope">
          {{ scope.row.barCode }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="商品类别">
        <template slot-scope="scope">
          {{ scope.row.topCategoryName }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="商品子类">
        <template slot-scope="scope">
          {{ scope.row.secondCategoryName }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="商品图片">
        <template slot-scope="scope">
          <img style="width: 40px;" :src="scope.row.img" alt="">
        </template>
      </el-table-column>
      <!-- <el-table-column align="header-center" label="建议销售">
        <template slot-scope="scope">
          {{ scope.row.phone }}
        </template>
      </el-table-column> -->
      <el-table-column align="center" fixed="right" label="操作" width="160">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope)">
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>

<el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑商品':'新增商品'">
      <el-form :model="role" :rules="rules" ref="ruleForm" label-width="160px" label-position="left">
        <el-form-item label="商品名称" prop="normal.name">
          <el-input v-model="role.normal.name" placeholder="商品名称" />
        </el-form-item>
        <el-form-item label="商品条码" prop="normal.barCode">
          <el-input v-model="role.normal.barCode" placeholder="商品条码" />
        </el-form-item>
        <el-form-item label="商品分类" prop="topCategoryId">
          <el-cascader :options="orderList" :props="{value:'id',label:'name'}" v-model="productClassId"></el-cascader>
        </el-form-item>
        <el-form-item label="商品包装" prop="packageType">
          <el-select v-model="role.normal.packageType" placeholder="商品包装">
            <el-option
              v-for="item in $store.state.user.goodBox"
              :key="item.value"
              :label="item.name"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品规格" prop="specs">
          <el-input style="width: 150px;margin-right: 20px;" v-model="role.normal.specs"  placeholder="ml/g"/>
        </el-form-item>
        <el-form-item label="商品重量" prop="weight">
          <el-input v-model="role.normal.weight" placeholder="商品重量" />
        </el-form-item>
        <el-form-item label="长*宽*高(毫米)" prop="name">
          <el-input style="width: 150px;" v-model="role.normal.length" placeholder="长" /> *
          <el-input style="width: 150px;" v-model="role.normal.width" placeholder="宽" /> *
          <el-input style="width: 150px;" v-model="role.normal.height" placeholder="高" />
        </el-form-item>
        <el-form-item label="商品图片" prop="pics">
          <el-row>
            <el-col :span="12">
              <div>商品正面带顶图片</div>
              <el-upload
                class="avatar-uploader"
                action="https://product-images-list.oss-cn-beijing.aliyuncs.com"
                :show-file-list="false"
                :on-success="handleAvatarSuccess1"
                :before-upload="beforeAvatarUpload1">
                <img v-if="role.normal.pics.frontTopUrl" :src="role.normal.pics.frontTopUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-col>
            <el-col :span="12">
              <div>商品背面带顶图片</div>
              <el-upload
                class="avatar-uploader"
                action="https://product-images-list.oss-cn-beijing.aliyuncs.com"
                :show-file-list="false"
                :on-success="handleAvatarSuccess2"
                :before-upload="beforeAvatarUpload2">
                <img v-if="role.normal.pics.backTopUrl" :src="role.normal.pics.backTopUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <div>商品正面带底图片</div>
              <el-upload
                class="avatar-uploader"
                action="https://product-images-list.oss-cn-beijing.aliyuncs.com"
                :show-file-list="false"
                :on-success="handleAvatarSuccess3"
                :before-upload="beforeAvatarUpload3">
                <img v-if="role.normal.pics.frontBottomUrl" :src="role.normal.pics.frontTopUrlfrontBottomUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-col>
            <el-col :span="12">
              <div>商品背面带底图片</div>
              <el-upload
                class="avatar-uploader"
                action="https://product-images-list.oss-cn-beijing.aliyuncs.com"
                :show-file-list="false"
                :on-success="handleAvatarSuccess4"
                :before-upload="beforeAvatarUpload4">
                <img v-if="role.normal.pics.backBottomUrl" :src="role.normal.pics.frontTopUrlbackBottomUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <div>商品左侧45度图片</div>
              <el-upload
                class="avatar-uploader"
                action="https://product-images-list.oss-cn-beijing.aliyuncs.com"
                :show-file-list="false"
                :on-success="handleAvatarSuccess5"
                :before-upload="beforeAvatarUpload5">
                <img v-if="role.normal.pics.left45Url" :src="role.normal.pics.frontTopUrlleft45Url" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-col>
            <el-col :span="12">
              <div>商品右侧45度图片</div>
              <el-upload
                class="avatar-uploader"
                action="https://product-images-list.oss-cn-beijing.aliyuncs.com"
                :show-file-list="false"
                :on-success="handleAvatarSuccess6"
                :before-upload="beforeAvatarUpload6">
                <img v-if="role.normal.pics.right45Url" :src="role.normal.pics.frontTopUrlright45Url" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">
          取消
        </el-button>
        <el-button type="primary" @click="confirm('ruleForm')">
          确定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogFillBuckle" v-if="productType=='del'" title="删除商品">
      <el-table :data="multipleSelection" style="margin-top:30px;" border>
        <!-- <el-table-column
          type="selection">
        </el-table-column> -->
        <el-table-column align="center" prop="name" label="名称" width="220">
          <template slot-scope="scope">
            {{ scope.row.name}}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="name" label="类别" width="220">
          <template slot-scope="scope">
            {{ scope.row.barcode }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="状态">
          <template slot-scope="scope">
            {{ scope.row.barcode }}
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align:right;margin-top: 40px;">
        <el-button type="danger" @click="dialogFillBuckle=false">
          取消
        </el-button>
        <el-button type="primary" @click="confirmDele">
          确定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogAddBuckle" v-if="productType=='join'" title="加入公司商品库">
      <el-form :model="role" :rules="rules" label-position="left">
        <el-form-item label="所属公司">
          <el-select v-model="formInline.gongsiSel" placeholder="所属公司">
            <el-option v-for="val in gongsiList" :key="val.id" :label="val.name" :value="val.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-table :data="multipleSelection" style="width: 100%;margin-top:30px;" border>
        <el-table-column align="center" label="名称" width="220">
          <template slot-scope="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="成本价" width="220">
          <template slot-scope="scope">
            <el-input v-model="joinProductPostData.onSalesProducts[scope.$index].cost" placeholder="成本价" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="售价">      
          <template slot-scope="scope">
            <el-input v-model="joinProductPostData.onSalesProducts[scope.$index].price" placeholder="售价" />
          </template>    
        </el-table-column>
      </el-table>
      <div style="text-align:right;margin-top: 40px;">
        <el-button type="danger" @click="dialogAddBuckle=false">
          取消
        </el-button>
        <el-button type="primary" @click="confirmJoin">
          确定
        </el-button>
      </div>
    </el-dialog>
    <Pagination :total="total" :page="page+1" @pagination="pagination" />
  </div>
</template>

<script>
import { deepClone } from '@/utils'
import { getGoods, getGoodsList, postGoodsBatchRemove, postGoodsList, postGoodsCloud, putGoods } from '@/api/Goods'
import { onsaleMaintain } from '@/api/TenantGoods'
import { category } from '@/api/user'
import Pagination from '@/components/Pagination/index'

const defaultRole = {
  "createUserId": "",
  "lastModifiedUserId": "",
  "type": 0,
  "normal": {
    "name": "",
    "barCode": "",
    "brandName": "",
    "topCategoryId": "",
    "secondCategoryId": "",
    "packageType": 0,
    "length": 0,
    "width": 0,
    "height": 0,
    "weight": 0,
    "specs": 0,
    "price": 0,
    "notes": "",
    "pics": {
      "frontTopUrl": "",
      "backTopUrl": "",
      "frontBottomUrl": "",
      "backBottomUrl": "",
      "left45Url": "",
      "right45Url": ""
    }
  }
}
//role.normal.pics.frontTopUrl
export default {
  data() {
    return {
      productType: 'join',
      dialogAddBuckle: false,
      productClassId: [],
      role: Object.assign({}, defaultRole),
      routes: [],
      dataList: [],
      dialogVisible: false,
      dialogFillBuckle: false,
      dialogRefund: false,
      dialogType: 'new',
      rules: {
        normal:{
          name: [
            { required: true, message: '请输入商品名称' },
          ],
          barCode: [
            { required: true, message: '请输入条码' },
          ],
        },
        topCategoryId: [
          { required: true, message: '请选择商品分类' },
        ],
        // packageType: [
        //   { required: true, message: '请选择商品规格' },
        // ],
        // phone: [
        //   { required: true, message: '请输入联系方式' },
        // ],
      },
      orderList: [],
      total: 0,
      page: 0,
      formInline: {
        gongsiSel: ''
      },
      checkoutData: {
        name:'',
        categoryId: [],
        gongsiSel: ''
      },
      gongsiSel:'',
      gongsiList:[],
      multipleSelection:[],
      joinProductPostData:{
        "tenantId": "",
        "onSalesProducts": [
          {
            "productId": "",
            "merchantName": "",
            "name": "",
            "cost": 0,
            "price": 0,
            "discount": 0,
            "comment": ""
          }
        ]
      },
      goodId:'',
    }
  },
  computed: {
    },
  components: { Pagination },
  created() {
    this.gongsiList = JSON.parse(localStorage.getItem('companyList'));
    this.formInline.gongsiSel = this.gongsiList[0].id;
    this.initData();
    this.orderListData();
  },
  methods: {
    //列表
    initData(){
      var data = {
          searchCriteria: {
            name: this.checkoutData.name,
            barCode: "",
            type: 0,
            categoryId: this.checkoutData.categoryId
          },
          pageCount: 10,
          page: this.page
        };
        if(this.checkoutData.categoryId.length == 0){
          delete data.searchCriteria.categoryId;
        }else{
          data.searchCriteria.categoryId = this.checkoutData.categoryId[this.checkoutData.categoryId.length-1];
        }
      postGoodsList(data).then((res)=>{
        console.log(res)
        this.dataList = res.result.normal;
        this.total = res.result.totalCount;
      })
    },
    //table选择的商品
    handleSelectionChange(val) {
      console.log(val)
      this.multipleSelection = val;
    },
    //加入公司商品库
    confirmJoin(){
      this.joinProductPostData.tenantId = this.formInline.gongsiSel;
      onsaleMaintain(this.joinProductPostData).then((res)=>{
        this.$message({
          type: 'success',
          message: '加入成功!'
        })
        this.dialogAddBuckle=false;
        console.log(res)
      })
// onsaleMaintain
    },
    openJoinPage(){
      this.dialogAddBuckle = true;
      this.productType = 'join';
      this.joinProductPostData.onSalesProducts = [];
      if(this.multipleSelection.length>0){
        for(let i=0;i<this.multipleSelection.length;i++){
          var obj = {
            "productId": this.multipleSelection[i].id,
            "merchantName": "",
            "name": this.multipleSelection[i].name,
            "cost": 0,
            "price": 0,
            "discount": 0,
            "comment": ""
          };
          this.joinProductPostData.onSalesProducts.push(obj);
        }
      }
    },
    //删除商品
    confirmDele(){
      this.$confirm('确认删除?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          var arr = [];
          for(let i = 0;i<this.multipleSelection.length;i++){
            arr.push(this.multipleSelection[i].id)
          }
          postGoodsBatchRemove(arr).then((res)=>{
            // this.dialogFillBuckle = false;
            if(res.result.fails && res.result.fails.length>0){
              this.$message({
                type: 'error',
                message: res.result.fails[0].reason
              })
            }else{
              this.initData();
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            }
          })
        })
        .catch(err => { console.error(err) })
    },
    //商品分类
    orderListData(){
      category().then((res)=>{
        console.log(res)
        this.orderList = res.result;
      })
    },
    //获取选择的商品类别
    goodClassChange(data){
      console.log(data)
      this.initData();
    },
    handleAvatarSuccess1(res, file) {
      this.role.normal.pics.frontTopUrl = URL.createObjectURL(file.raw);
    },
    handleAvatarSuccess2(res, file) {
      this.role.normal.pics.backTopUrl = URL.createObjectURL(file.raw);
    },
    handleAvatarSuccess3(res, file) {
      this.role.normal.pics.frontBottomUrl = URL.createObjectURL(file.raw);
    },
    handleAvatarSuccess4(res, file) {
      this.role.normal.pics.backBottomUrl = URL.createObjectURL(file.raw);
    },
    handleAvatarSuccess5(res, file) {
      this.role.normal.pics.left45Url = URL.createObjectURL(file.raw);
    },
    handleAvatarSuccess6(res, file) {
      this.role.normal.pics.right45Url = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload1(file) {
      const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    beforeAvatarUpload2(file) {
      const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    beforeAvatarUpload3(file) {
      const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    beforeAvatarUpload4(file) {
      const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    beforeAvatarUpload5(file) {
      const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    beforeAvatarUpload6(file) {
      const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    //重置
    handleReset(){
      this.checkoutData = {
        name:'',
        categoryId: [],
        gongsiSel: ''
      };
      this.initData();
    },
    //过滤查询
    check(){
      this.initData();
    },
    //分页
    pagination(data) {
      console.log(data)
      this.page = data.page-1;
      this.initData();
    },
    handleAdd() {
      this.role = Object.assign({}, defaultRole)
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    handleEdit(scope) {
      getGoods(scope.row.id).then((res)=>{
        console.log(res)
        this.dialogType = 'edit';
        this.dialogVisible = true;
        this.goodId = scope.row.id;
        this.role.normal = res.result.normal;
        this.role.type = res.result.type;
        this.productClassId = [res.result.normal.topCategoryId,res.result.normal.secondCategoryId];
        this.role.lastModifiedUserId = JSON.parse(localStorage.getItem('user_id'));
      })
    },
    async confirm(formName) {
      if(this.dialogType == 'edit'){
        delete this.role.createUserId;
        putGoods(this.goodId,this.role).then((res)=>{
          this.dialogVisible = false;
          this.initData();
          this.$message({
            type: 'success',
            message: '编辑成功!'
          })
        })
      }else{
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.role.createUserId = JSON.parse(localStorage.getItem('user_id'));
            this.role.lastModifiedUserId = JSON.parse(localStorage.getItem('user_id'));
            var list = this.role;
            if(this.productClassId.length == 0){
              delete list.normal.topCategoryId;
              delete list.normal.secondCategoryId;
            }else if(this.productClassId.length == 1){
              list.normal.topCategoryId = this.productClassId[0];
              this.role.normal.topCategoryId = this.productClassId[0];
              delete list.normal.secondCategoryId;
            }else{
              list.normal.topCategoryId = this.productClassId[0];
              list.normal.secondCategoryId = this.productClassId[1];
              this.role.normal.topCategoryId = this.productClassId[0];
              this.role.normal.secondCategoryId = this.productClassId[1];
            }
            postGoodsCloud(list).then((res)=>{
              this.dialogVisible = false
              this.initData();
              this.$message({
                type: 'success',
                message: '创建成功!'
              })
            })
          }else{
            return
          }
        })
      }
    },
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
 .avatar-uploader {
    width: 178px;
    height: 178px;
 }
 .avatar-uploader,.el-upload {
    border: 1px dashed #969696;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
